package com.base.im.server.netty.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




public class EchoServer {
	
	
	private static final Logger logger = LoggerFactory.getLogger(EchoServer.class);

	private static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

    public static void main(String[] args) throws Exception {
    	
    	

        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
        	
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 100)
//             .handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                	 
                	 ch.pipeline().addLast("decoder", new StringDecoder());  
                     ch.pipeline().addLast("encoder", new StringEncoder()); 
                     
                     ChannelPipeline p = ch.pipeline();
//                     p.addLast(new LoggingHandler(LogLevel.INFO));
                     p.addLast(new EchoServerHandler());
                 }
             });

            
            
            // Start the server.
            ChannelFuture f = b.bind(PORT).sync();            
            logger.error("服务端启动 端口为"+PORT);
            
//            Thread msgTestThread =new Thread(new MsgTestThread());
//            msgTestThread.start();
           
            
            
            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
            
            
           
            
            
            
        }catch(Exception e){
        	
        	logger.error("netty启动异常 原因["+e+"]");
        }finally {
        	
        	
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
  
 
	
	
}
